from ntpath import isdir
import os

def find_files_by_keyword(search_dir, keyword, recursive=True):
    """
    在指定目录中查找包含关键字的文件名
    参数：
        search_dir: 要搜索的目录路径
        keyword: 要查找的文件名关键字
        recursive: 是否递归搜索子目录 (默认True)
    返回：
        匹配文件的完整路径列表
    """
    matched_files = []
    
    try:
        if recursive:
            # 递归遍历所有子目录
            for root, dirs, files in os.walk(search_dir):
                for file in files:
                    if keyword in file:
                        matched_files.append(os.path.join(root, file))
        else:
            # 仅检查当前目录
            for file in os.listdir(search_dir):
                full_path = os.path.join(search_dir, file)
                if os.path.isfile(full_path) and keyword in file:
                    matched_files.append(full_path)
                    
        return matched_files
        
    except FileNotFoundError:
        raise ValueError(f"目录不存在: {search_dir}")
    except PermissionError:
        raise RuntimeError(f"无权限访问目录: {search_dir}")

def find_dir_by_keyword(search_dir, keyword, recursive=True):
    """
    在指定目录中查找包含关键字的文件名
    参数：
        search_dir: 要搜索的目录路径
        keyword: 要查找的文件名关键字
        recursive: 是否递归搜索子目录 (默认True)
    返回：
        匹配文件的完整路径列表
    """
    matched_dirs = []
    
    try:
        if recursive:
            # 递归遍历所有子目录
            for root, dirs, files in os.walk(search_dir):
                for dir in dirs:
                    if keyword in dir:
                        matched_dirs.append(os.path.join(root, dir))
        else:
            # 仅检查当前目录
            for dir in os.listdir(search_dir):
                full_path = os.path.join(search_dir, dir)
                if os.path.isdir(full_path) and keyword in dir:
                    matched_dirs.append(full_path)
                    
        return matched_dirs
        
    except FileNotFoundError:
        raise ValueError(f"目录不存在: {search_dir}")
    except PermissionError:
        raise RuntimeError(f"无权限访问目录: {search_dir}")

def rename_matched_files(file_list, keyword):
    """重命名匹配到的文件（从文件名中删除关键字）"""
    renamed_count = 0
    for old_path in file_list:
        dir_name = os.path.dirname(old_path)
        old_name = os.path.basename(old_path)
        new_name = old_name.replace(keyword, '')
        
        # 跳过无变化的文件
        if new_name == old_name:
            continue
            
        new_path = os.path.join(dir_name, new_name)
        
        try:
            os.rename(old_path, new_path)
            print(f"重命名成功: {old_path} -> {new_path}")
            renamed_count += 1
        except Exception as e:
            print(f"重命名失败 [{old_path}]: {str(e)}")
    
    return renamed_count
    
def rename_matched_dirs(dir_list, keyword):
    """重命名匹配到的文件（从文件名中删除关键字）"""
    renamed_count = 0
    for old_path in dir_list:
        dir_name = os.path.dirname(old_path)
        old_name = os.path.basename(old_path)
        new_name = old_name.replace(keyword, '')
        
        # 跳过无变化的文件
        if new_name == old_name:
            continue
            
        new_path = os.path.join(dir_name, new_name)
        
        try:
            os.rename(old_path, new_path)
            print(f"重命名成功: {old_path} -> {new_path}")
            renamed_count += 1
        except Exception as e:
            print(f"重命名失败 [{old_path}]: {str(e)}")
    
    return renamed_count

def handle_files(search_dir, keyword, recursive=True, rename_flag=True):
    try:
        result = find_files_by_keyword(
            search_dir=dir_name,
            keyword=keyword,
            recursive=True
        )
        
        print(f"找到 {len(result)} 个匹配文件：")
        for path in result:
            print(f"→ {path}")
        
        # 新增重命名操作
        if rename_flag and result:
            success_count = rename_matched_files(result, keyword)
            print(f"\n成功重命名 {success_count}/{len(result)} 个文件")
                
            
    except Exception as e:
        print(f"文件查找失败: {str(e)}")

def handle_dirs(search_dir, keyword, recursive=True):
    try:
        result = find_dir_by_keyword(
            search_dir=dir_name,
            keyword=keyword,
            recursive=True
        )
        
        print(f"找到 {len(result)} 个匹配文件：")
        for path in result:
            print(f"→ {path}")
        
        # 新增重命名操作
        if result:
            success_count = rename_matched_dirs(result, keyword)
            print(f"\n成功重命名 {success_count}/{len(result)} 个文件")
                
            
    except Exception as e:
        print(f"文件查找失败: {str(e)}")        

if __name__ == '__main__':
    #keyword = "【[db标签]】"
    keyword = "20171114-"
    #keyword = "20171115-"
    rename_flag = False
    dir_name = "F://download//ttns"
    #handle_files(dir_name, keyword, recursive=True, rename_flag=rename_flag)
    handle_dirs(dir_name, keyword)